package com.xxx.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xxx.constant.VerificationConstant;
import com.xxx.domain.PayOrder;
import com.xxx.exception.GlobleBussnessException;
import com.xxx.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 消费订单发送的事务消息
 */
@RocketMQMessageListener(
        consumerGroup = "station-pay-consumer"
        , topic = VerificationConstant.MQ_TOPIC_0RDER
        , selectorExpression = VerificationConstant.MQ_TAGS_COURSEORDER_PAYORDER
)
@Component
@Slf4j
public class MQTXConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 获取到消息
            if (messageExt != null && messageExt.getBody() != null && messageExt.getBody().length > 0) {
                byte[] body = messageExt.getBody();
                String s = new String(body, StandardCharsets.UTF_8);
                // 转换成对象
                PayOrder payOrder = JSON.parseObject(s, PayOrder.class);
                //String courseId = payOrder.getCourseId();
                ////payOrder.setExtParams(courseId);
                EntityWrapper<PayOrder> wrapper = new EntityWrapper<>();
                wrapper.eq("order_no", payOrder.getOrderNo());
                PayOrder payOrderFromDB = payOrderService.selectOne(wrapper);

                if (payOrderFromDB != null) {
                    log.info("订单已经存在，无需处理, 订单号: {}", payOrder.getOrderNo());
                    return;
                } else {
                    log.info("订单不存在，开始处理, 订单号: {}", payOrder.getOrderNo());
                    // 保存支付订单
                    payOrderService.insert(payOrder);
                }
            } else {
                log.warn("收到空消息或消息体为空");
            }
        } catch (Exception e) {
            log.error("处理支付订单消息失败: ", e);
            throw new GlobleBussnessException("生成支付单失败: " + e.getMessage());
        }
    }
}
